package pers.chy.chyappointmentplatform.Service;


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import pers.chy.chyappointmentplatform.Mapper.HisMapper.Ms_BrdaMapper;
import pers.chy.chyappointmentplatform.Mapper.HisMapper.Yjyy_PdjhMapper;
import pers.chy.chyappointmentplatform.Model.Ms_BrdaDTO;
import pers.chy.chyappointmentplatform.Model.Yjyy_PdjhDTO;
import pers.chy.chyappointmentplatform.Utils.ChyException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 对外交互服务类
 */
@Service
public class InteractiveService {

    @Autowired
    private Ms_BrdaMapper ms_BrdaMapper; //注入Mapper接口
    @Autowired
    private Yjyy_PdjhMapper yjyy_pdjhMapper;

    /**
     * 排队取号
     *
     * @param msg
     * @return
     * @throws Exception 失败时，主动向上抛出异常
     */
    /*
        设置事务隔离级别为串行化执行，防止“幻读”
        （一个用户select表中最大的排队号码后，另一个用户又insert了一条排队号，导致第一个用户插入重复的排队号）
     */
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public String doTakeQueueNumber(String msg) throws Exception {

        try {

            // 解析XML消息文档
            Document xmlDoc = DocumentHelper.parseText(msg);
            Element root = xmlDoc.getRootElement();             // 根节点
            Element msgHeaderNode = root.element("MsgHeader");  // 消息头
            Element msgBodyNode = root.element("MsgBody");      // 消息体
            String brkh = msgBodyNode.elementTextTrim("BRKH");      // 病人卡号
            String ywlx = msgBodyNode.elementTextTrim("YWLX");      // 业务类型
            String other = msgBodyNode.elementTextTrim("OTHER");    // 其他信息
            System.out.println("【接收XML】：" + brkh + ywlx + other);

            // 获取病人档案信息
            Ms_BrdaDTO ms_brdaDTO = ms_BrdaMapper.selectByJzkh(brkh);
            if (ms_brdaDTO == null) {
                throw new ChyException("取号失败，此卡未建档！");
            }
            // 当日已在排队且未叫号的不再取号,自助机屏幕上显示原号码
            // 当日已在排队且已叫号的不再取号,自助机屏幕上显示原号码
            // 当日已在排队且已过号的允许重新取号
            Date now = new Date();
            List<Yjyy_PdjhDTO> todayPdxxList = yjyy_pdjhMapper.selectForBeforeQh(ms_brdaDTO.getBRID(), new SimpleDateFormat("yyyy-MM-dd").format(now));
            for (Yjyy_PdjhDTO temp : todayPdxxList) {
                if (temp.getJhzt() == 0)
                    throw new ChyException("取号失败，请勿重复取号！您的排队号是:" + temp.getPdhm() + "(未叫号)");
                if (temp.getJhzt() == 1)
                    throw new ChyException("取号失败，请勿重复取号！您的排队号是:" + temp.getPdhm() + "(已叫号)");
            }

            // 获取当日最大的排队号码
            Yjyy_PdjhDTO todayMaxRecord = yjyy_pdjhMapper.selectMaxRecordToday(1);  // 暂时写死

            // 数据准备
            Yjyy_PdjhDTO entity = new Yjyy_PdjhDTO();
            entity.setPdhm(todayMaxRecord == null ? 1 : todayMaxRecord.getPdhm() + 1);
            entity.setBrid(ms_brdaDTO.getBRID());
            entity.setBrxm(ms_brdaDTO.getBrxm());
            entity.setJzlx(1);  // 就诊类型 暂时都设为1（门诊）
            entity.setJzhm(ms_brdaDTO.getMzhm());
            entity.setBzxx(other);
            entity.setYysj(now);
            entity.setYwlx(Integer.parseInt(ywlx));
            entity.setJjbz(0);  // 直接取号的，默认紧急标志=0
            entity.setQdbz(1);  // 直接取号的，默认签到标志=1
            if(entity.getYwlx() == 1){ // 队列信息
                entity.setDlxh(1);
                entity.setDlmc("PICC队列");   // 以后需改为从数据库中获取队列名称
            }

            // 插入排队取号表
            yjyy_pdjhMapper.insert(entity);

            // 创建要返回的XML
            Document document = DocumentHelper.createDocument();
            Element rootNode = document.addElement("MsgBody");
            rootNode.addElement("QueueNumber").addText(String.valueOf(entity.getPdhm()));
            rootNode.addElement("BRXM").addText(ms_brdaDTO.getBrxm());
            rootNode.addElement("QHSJ").addText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now));

            //
            return document.getRootElement().asXML();
        } catch (Exception ex) {
            throw ex;
        }

    }
}
